package cn.com.blueInfo.bpm.person.repository.impl;

import cn.com.blueInfo.bpm.common.entity.BaseEntity;
import cn.com.blueInfo.bpm.common.enums.BaseDeleted;
import cn.com.blueInfo.bpm.common.repository.BaseRepository;
import cn.com.blueInfo.bpm.person.entity.UserAccount;
import cn.com.blueInfo.bpm.person.enums.UserAccountMfaStatus;
import cn.com.blueInfo.bpm.person.enums.UserAccountStatus;
import cn.com.blueInfo.bpm.person.mapper.UserAccountMapper;
import cn.com.blueInfo.bpm.person.repository.UserAccountRepository;
import cn.com.blueInfo.bpm.person.request.UserAccountDTO;
import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 员工账户表 数据服务实现类
 * @author suxch
 * @since 2025-09-01 19:28:09
 */
@Log4j2
@Service
public class UserAccountRepositoryImpl
        extends ServiceImpl<UserAccountMapper, UserAccount>
        implements UserAccountRepository, BaseRepository<UserAccount, UserAccountDTO.QueryDTO> {

    @Autowired
    private CurrentLoginUserInfo currentLoginUserInfo;

    /**
     * 提供获取 CurrentLoginUserInfo 的方法（由实现类提供，避免接口中注入）
     * @return CurrentLoginUserInfo
     */
    @Override
    public CurrentLoginUserInfo getCurrentLoginUserInfo() {
        return currentLoginUserInfo;
    }

    /**
     * 新增员工账户
     * @param userAccount 员工账户参数
     */
    @Override
    public Integer createUserAccount(UserAccount userAccount) {
        return sqlExecuteResult(save(userAccount));
    }

    /**
     * 批量新增员工账户
     * @param userAccountList 员工账户参数列表
     */
    @Override
    public Integer batchCreateUserAccount(List<UserAccount> userAccountList) {
        return sqlExecuteResult(saveBatch(userAccountList), userAccountList.size());
    }

    /**
     * 删除员工账户
     * @param userAccountId 员工账户ID
     */
    @Override
    public Integer deleteUserAccount(Long userAccountId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userAccountId);
        userAccount.setDeleted(BaseDeleted.DELETED);
        return sqlExecuteResult(removeById(userAccount));
    }

    /**
     * 批量删除员工账户
     * @param userAccountIdList 员工账户ID列表
     */
    @Override
    public Integer batchDeleteUserAccount(List<Long> userAccountIdList) {
        List<UserAccount> userAccountList = new ArrayList<>();
        for (Long userAccountId : userAccountIdList) {
            UserAccount userAccount = new UserAccount();
            userAccount.setId(userAccountId);
            userAccount.setDeleted(BaseDeleted.DELETED);
        }
        return sqlExecuteResult(removeBatchByIds(userAccountList), userAccountList.size());
    }

    /**
     * 更新部分员工账户
     * @param userAccount 员工账户参数
     */
    @Override
    public Integer updateUserAccountPartial(UserAccount userAccount) {
        validateUpdateId(userAccount.getId());
        LambdaUpdateWrapper<UserAccount> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserAccount::getId, userAccount.getId());
        return sqlExecuteResult(update(updateWrapper));
    }

    /**
     * 更新全部员工账户
     * @param userAccount 员工账户参数
     */
    @Override
    public Integer updateUserAccount(UserAccount userAccount) {
        validateUpdateId(userAccount.getId());
        return sqlExecuteResult(updateById(userAccount));
    }

    /**
     * 查询一条员工账户
     * @param userAccountId 员工账户ID
     */
    @Override
    public UserAccount getUserAccountById(Long userAccountId) {
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getId, userAccountId);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询员工账户
     * @param userAccountQueryDTO 员工账户参数
     */
    @Override
    public Page<UserAccount> getUserAccountPage(UserAccountDTO.QueryDTO userAccountQueryDTO) {
        Page<UserAccount> userAccountPage = new Page<>(
                userAccountQueryDTO.getPage(), userAccountQueryDTO.getSize());
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, userAccountQueryDTO);

        BaseDeleted deleted = userAccountQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeletePage(userAccountPage, queryWrapper);
        } else {
            return page(userAccountPage, queryWrapper);
        }
    }

    /**
     * 根据条件查询 员工账户 数量
     * @param userAccountQueryDTO 员工账户参数
     */
    @Override
    public Long getUserAccountCount(UserAccountDTO.QueryDTO userAccountQueryDTO) {
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, userAccountQueryDTO);

        BaseDeleted deleted = userAccountQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteCount(queryWrapper);
        } else {
            return count(queryWrapper);
        }
    }

    /**
     * 根据条件查询 员工账户
     * @param userAccountQueryDTO 员工账户参数
     */
    @Override
    public List<UserAccount> getUserAccountList(UserAccountDTO.QueryDTO userAccountQueryDTO) {
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper(queryWrapper, userAccountQueryDTO);

        BaseDeleted deleted = userAccountQueryDTO.getDeleted();
        if (ObjectUtils.isNotEmpty(deleted) && deleted.equals(BaseDeleted.DELETED)) {
            return baseMapper.selectDeleteList(queryWrapper);
        } else {
            return list(queryWrapper);
        }
    }

    private void queryWrapper(LambdaQueryWrapper<UserAccount> queryWrapper,
                              UserAccountDTO.QueryDTO userAccountQueryDTO) {

        Long userBaseId = userAccountQueryDTO.getUserBaseId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(userBaseId), UserAccount::getUserBaseId, userBaseId);

        String loginName = userAccountQueryDTO.getLoginName();
        queryWrapper.eq(StringUtils.isNotBlank(loginName), UserAccount::getLoginName, loginName);

        String loginMobile = userAccountQueryDTO.getLoginMobile();
        queryWrapper.eq(StringUtils.isNotBlank(loginMobile), UserAccount::getLoginMobile, loginMobile);

        String loginEmail = userAccountQueryDTO.getLoginEmail();
        queryWrapper.eq(StringUtils.isNotBlank(loginEmail), UserAccount::getLoginEmail, loginEmail);

        String password = userAccountQueryDTO.getPassword();
        queryWrapper.eq(StringUtils.isNotBlank(password), UserAccount::getPassword, password);

        LocalDateTime passwordExpireTime = userAccountQueryDTO.getPasswordExpireTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(passwordExpireTime), UserAccount::getPasswordExpireTime, passwordExpireTime);

        UserAccountStatus accountStatus = userAccountQueryDTO.getAccountStatus();
        queryWrapper.eq(ObjectUtils.isNotEmpty(accountStatus), UserAccount::getAccountStatus, accountStatus);

        String lockReason = userAccountQueryDTO.getLockReason();
        queryWrapper.eq(StringUtils.isNotBlank(lockReason), UserAccount::getLockReason, lockReason);

        LocalDateTime lastLoginTime = userAccountQueryDTO.getLastLoginTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(lastLoginTime), UserAccount::getLastLoginTime, lastLoginTime);

        String lastLoginIp = userAccountQueryDTO.getLastLoginIp();
        queryWrapper.eq(StringUtils.isNotBlank(lastLoginIp), UserAccount::getLastLoginIp, lastLoginIp);

        Byte loginFailCount = userAccountQueryDTO.getLoginFailCount();
        queryWrapper.eq(ObjectUtils.isNotEmpty(loginFailCount), UserAccount::getLoginFailCount, loginFailCount);

        LocalDateTime loginFailTime = userAccountQueryDTO.getLoginFailTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(loginFailTime), UserAccount::getLoginFailTime, loginFailTime);

        UserAccountMfaStatus mfaStatus = userAccountQueryDTO.getMfaStatus();
        queryWrapper.eq(ObjectUtils.isNotEmpty(mfaStatus), UserAccount::getMfaStatus, mfaStatus);

        String mfaSecret = userAccountQueryDTO.getMfaSecret();
        queryWrapper.eq(StringUtils.isNotBlank(mfaSecret), UserAccount::getMfaSecret, mfaSecret);

        LocalDateTime accountExpireTime = userAccountQueryDTO.getAccountExpireTime();
        queryWrapper.eq(ObjectUtils.isNotEmpty(accountExpireTime), UserAccount::getAccountExpireTime, accountExpireTime);

        String loginChannel = userAccountQueryDTO.getLoginChannel();
        queryWrapper.eq(StringUtils.isNotBlank(loginChannel), UserAccount::getLoginChannel, loginChannel);

        addQueryWrapper(queryWrapper, userAccountQueryDTO, getCommonColumn());

    }

    private Map<String, SFunction<UserAccount, ?>> getCommonColumn() {
        return BaseEntity.getCommonColumn(
                UserAccount::getOrderNumber,
                UserAccount::getTenantId,
                UserAccount::getApplicationId,
                UserAccount::getStatus,
                UserAccount::getDeleted,
                UserAccount::getDeleteUserId,
                UserAccount::getDeleteTime,
                UserAccount::getRemark,
                UserAccount::getCreateUserId,
                UserAccount::getCreateTime,
                UserAccount::getUpdateUserId,
                UserAccount::getUpdateTime,
                UserAccount::getExtend1,
                UserAccount::getExtend2,
                UserAccount::getExtend3);
    }

}
